package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw10000204.R;

import logic.constants.DefaultConsts;
import logic.pay.PayResult;
import logic.pay.PayUtil;
import logic.util.MoneyUtil;
import logic.util.Utils;


/**
 * @project qysw_e-commerce
 * @description 订单支付页面
 * @author zhangnannan
 * @Time 2015年4月10日 下午4:08:34
 */
public class OrderPayActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	private Context   context;
	private TextView  tvTitle;
	private Button    btnBack;
	private Button    btnHome;
	private TextView  tvTotalMoney;
	
	private Button    btnEnsure;
	private ImageView ivChoosePayModeIcon;
	private boolean   isSelected = true;
	
	private int       money;              //付款总金额
	private String    orderSerial;        //订单序列号
	private String    orderTitle;         //订单标题
	private String    orderDetail;        //订单body
	private String    price;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_pay);
		context = this;
		
		orderSerial = getIntent().getExtras().getString(DefaultConsts.ORDER_DETAIL_ORDER_SERIAL);
		money = getIntent().getExtras().getInt(DefaultConsts.ORDER_DETAIL_ORDER_PAY_MONEY);
		orderTitle = getIntent().getExtras().getString(DefaultConsts.ORDER_DETAIL_ORDER_ORDER_TITLE);
		orderDetail = getIntent().getExtras().getString(DefaultConsts.ORDER_DETAIL_ORDER_ORDER_INTRO);
		price = Utils.getMoneyFormat(MoneyUtil.divide(money, 100));
		findView();
		addListener();
	}
	
	@SuppressLint ("HandlerLeak")
	private Handler handler = new Handler()
	                        {
		                        @Override
		                        public void handleMessage(Message msg) {
			                        switch (msg.what) {
										case PayUtil.SDK_PAY_FLAG: {
											PayResult payResult = new PayResult((String) msg.obj);
											
											// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
											String resultInfo = payResult.getResult();
											
											String resultStatus = payResult.getResultStatus();
											
											// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
											if (TextUtils.equals(resultStatus, "9000"))
											{
//												Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
												startActivity(new Intent(context, MyGoodsActivity.class));
												finish();
											}
											else
											{
												// 判断resultStatus 为非“9000”则代表可能支付失败
												// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
												if (TextUtils.equals(resultStatus, "8000"))
												{
													Toast.makeText(context, "支付结果确认中", Toast.LENGTH_SHORT).show();
													
												}
												else
												{
													// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
													Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
													
												}
											}
											break;
										}
										case PayUtil.SDK_CHECK_FLAG: {
											Toast.makeText(context, "是否有支付宝认证账号：" + msg.obj, Toast.LENGTH_SHORT).show();
											break;
										}
									}
								}
	                        };
	
	@Override
	public Handler getUIHandler() {
		// TODO Auto-generated method stub
		return handler;
	}
	
	/**
	 * 
	 */
	private void findView() {
		btnBack = (Button) findViewById(R.id.common_header_back);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		btnHome = (Button) findViewById(R.id.common_header_home);
		tvTitle.setText("支付订单");
		btnBack.setVisibility(View.VISIBLE);
		btnHome.setVisibility(View.VISIBLE);
		
		btnEnsure = (Button) findViewById(R.id.order_pay_ensure_btn);
		ivChoosePayModeIcon = (ImageView) findViewById(R.id.order_pay_choose_mode_status_icon_iv);
		ivChoosePayModeIcon.setSelected(isSelected);
		
		tvTotalMoney = (TextView) findViewById(R.id.order_pay_total_money_tv);
		tvTotalMoney.setText(price);
	}
	
	/**
	 * 
	 */
	private void addListener() {
		btnBack.setOnClickListener(this);
		btnHome.setOnClickListener(this);
		btnEnsure.setOnClickListener(this);
		ivChoosePayModeIcon.setOnClickListener(this);
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				startActivity(new Intent(context, MyGoodsActivity.class));
				finish();
				break;
			case R.id.common_header_home:
//				Intent intent = new Intent(context, MainActivity.class);
//				startActivity(intent);
				BaseSimpleActivity.gotoMainActivity();
				break;
			case R.id.order_pay_ensure_btn:
				clickPay();
				break;
			case R.id.order_pay_choose_mode_status_icon_iv:
				if (isSelected)
				{
					isSelected = false;
					ivChoosePayModeIcon.setSelected(isSelected);
				}
				else
				{
					isSelected = true;
					ivChoosePayModeIcon.setSelected(isSelected);
				}
				break;
			default:
				break;
		}
		
	}
	
	/**
	 * 
	 */
	private void clickPay() {
		if (isSelected)
		{
			
			//		PayUtil.getSDKVersion(OrderPayActivity.this, getUIHandler());
			//		PayUtil.check(OrderPayActivity.this, getUIHandler());
			final String orderInfo = PayUtil.getOrderInfo(orderSerial, orderTitle, orderDetail, "0.01");
			PayUtil.pay(OrderPayActivity.this, getUIHandler(), orderInfo);
		}else{
			Utils.showToast(context, "请选择支付方式");
		}
	}
	
}
